//IE支持placeholder
var JPlaceHolder = {
    //检测
    _check : function(){
        return 'placeholder' in document.createElement('input');
    },
    //初始化
    init : function(){
        if(!this._check()){
            this.fix();
        }
    },
    //修复
    fix : function(){
        jQuery(':input[placeholder]').each(function(index, element) {
            var self = $(this), txt = self.attr('placeholder');
            self.wrap($('<div></div>').css({position:'relative', zoom:'1', border:'none', background:'none', padding:'none', margin:'none'}));
            var pos = self.position(), h = self.outerHeight(true), paddingleft = self.css('padding-left');
            var holder = $('<span></span>').text(txt).css({position:'absolute', left:pos.left, top:pos.top, height:h, lienHeight:h, paddingLeft:paddingleft, color:'#aaa'}).appendTo(self.parent());
            self.focusin(function(e) {
                holder.hide();
            }).focusout(function(e) {
                if(!self.val()){
                    holder.show();
                }
            });
            holder.click(function(e) {
                holder.hide();
                self.focus();
            });
        });
    }
};
//执行
jQuery(function(){
    JPlaceHolder.init();
    $('textarea').css('resize','none');
});
jQuery.download = function(url, method, path){
    jQuery('<form action="'+url+'" method="'+(method||'post')+'">' +
        '<input type="text" name="path" value="'+path+'"/>' +
        '</form>')
        .appendTo('body').submit().remove();
};
String.prototype.trim = function(){
    return this.replace(/^\s+|\s+$/g, '');
};
String.prototype.format=function()
{
    if(arguments.length==0) return this;
    for(var s=this, i=0; i<arguments.length; i++)
        s=s.replace(new RegExp("\\{"+i+"\\}","g"), arguments[i]);
    return s;
};
String.prototype.dateFrom8=function(){
    var s=this;
    return (s &&(s.length==8))?s.substr(0,4)+'-'+s.substr(4,2)+'-'+s.substr(6,2):''
};

Date.prototype.format = function(format){
    var d=this;
    var o = {
        "M+" : d.getMonth()+1, //month
        "d+" : d.getDate(), //day
        "h+" : d.getHours(), //hour
        "m+" : d.getMinutes(), //minute
        "s+" : d.getSeconds(), //second
        "q+" : Math.floor((d.getMonth()+3)/3), //quarter
        "S" : d.getMilliseconds() //millisecond
    }

    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }

    for(var k in o) {
        if(new RegExp("("+ k +")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    }
    return format;
};
Date.prototype.addDate=function (days) {
    var d=this;
    d.setDate(d.getDate()+days);
    return d;
};
Date.prototype.addMinute=function (mins) {
    var d=this;
    var min=d.getMinutes();
    d.setMinutes(min+mins);
    return d;
};


Array.prototype.contains = function(item){
    return RegExp("\\b"+item+"\\b").test(this);
};
/**
 * 是否为空或空字符串
 */
function isNull(obj) {
    if(typeof(obj) == "undefined" || obj == null || !obj || ( typeof(obj) == "string" && obj.trim() == "" )) {
        return true;
    } else {
        return false;
    }
}
/**
 * 是否为整数
 */
function isNb(obj) {
    if(obj != null && obj != "" && obj.length > 0){
        if(obj.match( /^(-|\+)?\d+$/)!=null) {
            return false;
        } else {
            return true;
        }
    }
    return false;

}
function isNbMobile(obj) {
    if(obj != null && obj != "" && obj.length > 0){
        if(obj.match( /^(\d+,)*\d+$/)!=null) {
            return false;
        } else {
            return true;
        }
    }
    return false;
}
function isNumber( s ){
    if(s==null || s=="")
        return false;

    s = s + "";

    if(s.charAt(0) == '.') return false;

    var regu = "^\-?[0-9.]+$";
    var re = new RegExp(regu);
    if (s.search(re) != -1) {
        return true;
    } else {
        return false;
    }
    return true;
}
function isMoney( s ){
    if(s==null || s=="")
        return false;
    s = s + "";
    //不带负数 "^[0-9]+[\.]{0,1}[0-9]{0,2}$";
    var regu ="^[0-9]+[\.]{0,1}[0-9]{0,2}$";
    var re = new RegExp(regu);
    if (re.test(s)) {
        return true;
    } else {
        return false;
    }
}
function getCheckVal($obj) {
    var val,type=$obj[0].type;

    if(type=='password' || type=='text' || type=='email' || type=='textarea' || type=='email' || type=='number'|| type=='select-one'){
        val=$obj.val();
    }else if(type=='checkbox' || type=='radio'){
        if($obj.is(':checked')){
            val=$obj.val();
        }
    }
    return val;
}
function checkNull($obj) {
	var val=getCheckVal($obj);
	if(isNull(val)){
		$obj.removeClass('check-valid').addClass('check-error');
        layer.tips('不能为空', '#'+$obj.attr('id'),{tips:[3,'#78BA32']});
		return false;
	}
    $obj.addClass('check-valid').removeClass('check-error');
	return val;
}
function checkPassword($obj) {
	var val=getCheckVal($obj);
	if(!/^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&*-]+$)(?![a-zA-z\d]+$)(?![a-zA-z!@#$%^&*-]+$)(?![\d!@#$%^&*-]+$)[a-zA-Z\d!@#$%^&*-]{6,16}$/.test(val)){
		$obj.removeClass('check-valid').addClass('check-error');
        layer.tips('请输入6-16位必须包含数字、母组、特殊符号的密码', '#'+$obj.attr('id'),{tips:[2,'#78BA32']});
		return false;
	}
    $obj.addClass('check-valid').removeClass('check-error');
	return val;
}
function checkPassword1($obj) {
    var val=getCheckVal($obj);
    if(!/^[0-9a-zA-Z]{6,16}$/.test(val)){
        $obj.removeClass('check-valid').addClass('check-error');
        layer.tips('请输入6-16位数字或字母组成的密码', '#'+$obj.attr('id'),{tips:[3,'#78BA32']});
        return false;
    }
    $obj.addClass('check-valid').removeClass('check-error');
    return val;
}
function checkEmail($obj) {
	var val=getCheckVal($obj);
    var regEmail=/^((([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6}\;))*(([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})))$/;
	if(!regEmail.test(val)){
		$obj.removeClass('check-valid').addClass('check-error');
        layer.tips('请输入正确的电子邮件地址', '#'+$obj.attr('id'),{tips:[2,'#78BA32']});
		return false;
	}
    $obj.addClass('check-valid').removeClass('check-error');
	return val;
}
function checkMoney($obj) {
	var val=getCheckVal($obj);
	if(!isMoney(val)){
        $obj.removeClass('check-valid').addClass('check-error');
        layer.tips('请输入正确的金额', '#'+$obj.attr('id'),{tips:[2,'#78BA32']});
        return false;
    }
    $obj.addClass('check-valid').removeClass('check-error');
	return val;
}



function checknNb($obj) {
    var val=getCheckVal($obj);

    if(val.match( /^(-|\+)?\d+$/)==null) {
        $obj.removeClass('check-valid').addClass('check-error');
        layer.tips('只能输入正整数', '#'+$obj.attr('id'),{tips:[2,'#78BA32']});
        return false;
    }

    var min = $obj.attr('min');
    var max =  $obj.attr('max');
    if(min != undefined )
    {
        if(parseInt(val) < min)
        {
            $obj.removeClass('check-valid').addClass('check-error');
            layer.tips('最小不能小于'+min, '#'+$obj.attr('id'),{tips:[2,'#78BA32']});
            return false;
        }
    }
    if(max != undefined )
    {
        if(parseInt(val) > max)
        {
            $obj.removeClass('check-valid').addClass('check-error');
            layer.tips('最大不能超过'+max, '#'+$obj.attr('id'),{tips:[2,'#78BA32']});
            return false;
        }
    }

    $obj.addClass('check-valid').removeClass('check-error');
    return val;
}

function checkEqualTo($obj,$target) {
	var val=getCheckVal($obj);
	var tarval=getCheckVal($target);
	if(val!=tarval){
        $target.removeClass('check-valid').addClass('check-error');
        layer.tips('两次输入不一致', '#'+$target.attr('id'),{tips:[2,'#78BA32']});
		return false;
	}
    $target.addClass('check-valid').removeClass('check-error');
	return val;
}
function getForm(form){
    var datas=form.serializeArray();
    var obj={};
    for(var i=0;i<datas.length;i++){
        var exist=obj[datas[i].name];
        if(exist){
            var temp=[];
            var v=datas[i].value;
            if(v){
                temp.push(v);
                temp.push(exist);
                obj[datas[i].name]=temp.join(',');
            }
        }else{
            obj[datas[i].name]=datas[i].value;
        }
    }
    return obj;
}
function checkForm(form) {
    var check_go=true;
    form.find('input,select,textarea').each(function () {
        var _this=$(this),checks=_this.attr('check'),checkar=checks?checks.split(','):[];
        for(var i=0;i<checkar.length;i++){
            var check=checkar[i];
            if(check=='null' && !_this.val()){
                break;
            }else if(check=='notnull'){
                if((check_go=checkNull(_this))===false){
                    return false;
                }
            }else if(check=='password'){
                if((check_go=checkPassword(_this))===false){
                    return false;
                }
            }else if(check=='email'){
                if((check_go=checkEmail(_this))===false){
                    return false;
                }
            }else if(check=='isNb'){
                if((check_go=checknNb(_this))===false){
                    return false;
                }
            }else if(check=='money'){
                if((check_go=checkMoney(_this))===false){
                    return false;
                }
            }
        }
    });
    return check_go?getForm(form):check_go;
}
function clearForm(obj,notClears) {
    obj.find("input[type=text],input[type=number],input[type=email],input[type=hidden],input[type=password],select,textarea").not(notClears).each(function (i, o) {
        $(o).val('');
    });
}

function dialogBox(url,title,width,height,full) {
    // var layer=parent.layer?parent.layer:layer;
    var index = layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        scrollbar: false,
        shade: 0.3,
        area: [width+'px', height+'px'],
        content: url
    });
    if(full){
        layer.full(index);
    }
}
function dialogClose() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function createConfirm(content,callback){
    var l=parent.layer;
    if(!l){
        l=layer;
    }
    l.confirm(content, {icon: 3, title:'提示'}, function(index){
        if(callback){
            callback();
        }
        l.close(index);
    }, function(index){
        l.close(index);
    });
}
function showLoadingResult(msg) {
    // return layer.load(1, {
    //     msg:msg||'',
    //     shade: [0.3,'#000000'] //0.1透明度的白色背景
    // });

    var l=parent.layer;
    if(!l){
        l=layer;
    }
    var index = l.msg(msg||'加载中', {
        icon: 16
        ,time:100000000000
        ,shade: [0.3,'#000000']
    });
    return index;
}
function closeLoadingResult(index) {
    var l=parent.layer;
    if(!l){
        l=layer;
    }
    l.close(index);
}
function promptText(title,callback) {
    var l=parent.layer;
    if(!l){
        l=layer;
    }
    l.prompt({title: title, formType: 0}, function(pass, index){
        if($.isFunction(callback)){
            callback(pass,index);
        }
    });
}

function pageId() {
    var fid = window.frameElement.id,index=fid.indexOf('_tab');
    return fid.substr(index+1);
}
function closeCurrent(refresh) {
    if(refresh){
        parent.$('body').trigger('refresh');
    }
    tabClose(pageId());
}
function fixId(action) {
    return (action).replace(/[\/\?=\&(\u4e00-\u9fa5):\*\(\)\@\#\$\%\^\~\!\+\-,.\<\>\s]/g,'');
}
function reloadPage(url){
    window.location=(appPath+url);
}
function flushPage(url){
    window.location.replace(appPath+url);
}
function ajaxReloadPage(div,url){
    $('#'+div).load(appPath+url);
}
function reloadHash(hash){
    window.location.hash=hash;
}
function refresh() {
    window.location.reload();
}
function closeAlls() {
    tab.closeAll();
}

function alertSuccess(msg,callback){
    var l=parent.layer;
    if(!l){
        l=layer;
    }
    l.msg(!msg?'操作成功':msg, {time: 2000},callback);
}
function alertError(msg,callback){
    var l=parent.layer;
    if(!l){
        l=layer;
    }
    l.msg(msg || '操作失败', {time: 2000},callback);
}
function layer_alert(msg) {
    var l=parent.layer;
    if(!l){
        l=layer;
    }
    l.alert(msg)
}
function layer_close_all() {
    var l=parent.layer;
    if(!l){
        l=layer;
    }
    l.closeAll();
}

function alertNotify(msg,callback){
    layer.msg(msg, {time: 2000},callback);
}
function tips(msg,$obj) {
    layer.tips(msg, $obj,{tips:[2,'#78BA32']});
}
function ajaxError(response){
    var status= response.status;
    if(status==403){
        alertError('你没有足够权限');
    }else if(status==404){
        alertError('找不到访问地址');
    }else if(status==400){
        alertError('请求出错');
    }else if(status==500){
        alertError('服务器异常');
    }else{
        alertError("网路未知错误");
    }
}

function createAlert(msg,callback){
    return layer.alert(msg, {icon: 3},callback);
}
function ajaxComplete(XHR, TS){
    var timeout=XHR.getResponseHeader('sessionstatus');
    if(timeout=='timeout'){
        createAlert('你的登录已超时,请重新登录',function(){
        	if(parent){
        		parent.window.location.replace(appPath+'login');
			}else{
                window.location.replace(appPath+'login');
			}
        });
    }
}
function ajaxConfig(url,type,data,callback,timeout,contentType) {
    var config={
        url: appPath+url,
        type:type,
        timeout: timeout||180000,
        success: function (result) {
            if($.isFunction(callback)){
                callback(result);
            }
        },
        complete:ajaxComplete,
        error:ajaxError
    };
    if($.isFunction(data)){
        config.success=function (reuslt) {
            data(reuslt);
        }
    }else{
        config.data=data;
    }
    if(contentType=='json'){
    	config.contentType="application/json;charset=UTF-8";
        config.data=JSON.stringify(data);
	}
    return config;
}
function get(url,data,callback,timeout){
    $.ajax(ajaxConfig(url,"GET",data,callback,timeout));
}
function post(url,data,callback,timeout){
    $.ajax(ajaxConfig(url,"Post",data,callback,timeout));
}
function postJSON(url,data,callback,timeout){
    $.ajax(ajaxConfig(url,"Post",data,callback,timeout,'json'));
}

function sync(url,params){
    var temp;
    var config={
        async: false,
        type : "POST",
        url : appPath+url,
        success : function(data) {
            temp=data;
        },
        complete:ajaxComplete,
        error:ajaxError
    };
    if(data){
        config.data=data;
	}
    $.ajax(config);
    return temp;
}
/**
 * 客服端分页
 * @param table
 * @param columns
 * @param options
 * @param params
 */
function simpleTable(table,columns,options,params) {
    var datatable=$('#'+table);
    var url=options.url;
    var len=columns.length;
    var cc=[];
    for(var i=0;i<len;i++){
        var rec=columns[i];
        var type=rec.type;
        var mRender=rec.render;
        if(type=='date'){
            mRender=function (data, type, full) {
                return data?new Date(data).format('yyyy-MM-dd'):'';
            }
        }else if(type=='datetime'){
            mRender=function (data, type, full) {
                return data?new Date(data).format('yyyy-MM-dd hh:mm:ss'):'';
            }
        }
        var c={
            mDataProp:rec.dataIndex,
            sTitle:rec.text||rec.header||rec.title,
            bSortable:rec.bSortable,
            sClass:rec.sClass,
            mRender:mRender
        }
        if(rec.sWidth){
            c.sWidth=rec.sWidth;//宽度
        }
        c=$.extend(c,rec);
        cc.push(c);
    }
    options=$.extend({
        bProcessing: true,
        bPaginate: true, //翻页功能
        bLengthChange: true, //改变每页显示数据数量
        bFilter: false, //过滤功能
        bSort: false, //排序功能
        bInfo: true,//页脚信息
        bAutoWidth: true,//自动宽度
        bServerSide: false, //指定从服务器端获取数据
        // pageLength: 30,//每页显示8条数据
        ajax: {
            url:url,
            dataSrc:'data',
            data:params
        },
        aoColumns:cc
    },options);
    return datatable.DataTable(options);
}
/**
 * 服务端分页
 * @param table
 * @param columns
 * @param ajaxoptions
 */

function ajaxServerTable(table,columns,ajaxoptions) {

    var datatable=$('#'+table);
    var len=columns.length;
    var cc=[];
    for(var i=0;i<len;i++){
        var rec=columns[i];
        var type=rec.type;
        var mRender=rec.render;
        if(type=='date'){
            mRender=function (data, type, full) {
                if(!data) return '';
                return new Date(data).format('yyyy-MM-dd');
            }
        }else if(type=='datetime'){
            mRender=function (data, type, full) {
                if(!data) return '';
                return new Date(data).format('yyyy-MM-dd hh:mm:ss');
            }
        }
        var c={
            mDataProp:rec.dataIndex,
            sTitle:rec.text||rec.header||rec.title,
            bSortable:rec.bSortable,
            sClass:rec.sClass,
            mRender:mRender
        }
        if(rec.sWidth){
        	c.sWidth=rec.sWidth;//宽度
		}
        c=$.extend(c,rec);
        cc.push(c);
    }
    var options=$.extend({
        iDisplayLength:25,
        bProcessing: false,
        bPaginate: true, //翻页功能
        bLengthChange: true, //改变每页显示数据数量
        bFilter: false, //过滤功能
        bSort: false, //排序功能
        bInfo: true,//页脚信息
        bAutoWidth: false,//自动宽度
        bServerSide: true, //指定从服务器端获取数据
        aoColumns:cc,
        columnDefs: [{
            targets:0,
            data: null,
            defaultContent:""
        }]
    },ajaxoptions);
    return datatable.DataTable(options);
}


/**
 * 服务端分页 包含复选框
 * @param table
 * @param columns
 * @param ajaxoptions
 */
function ajaxServerTableisCheck(table,columns,ajaxoptions) {
    var datatable=$('#'+table);
    var len=columns.length;
    var cc=[];
    for(var i=0;i<len;i++){
        var rec=columns[i];
        var type=rec.type;
        var mRender=rec.render;
        if(type=='date'){
            mRender=function (data, type, full) {
                if(!data) return '';
                return new Date(data).format('yyyy-MM-dd');
            }
        }else if(type=='datetime'){
            mRender=function (data, type, full) {
                if(!data) return '';
                return new Date(data).format('yyyy-MM-dd hh:mm:ss');
            }
        }
        var c={
            mDataProp:rec.dataIndex,
            sTitle:rec.text||rec.header||rec.title,
            bSortable:rec.bSortable,
            sClass:rec.sClass,
            mRender:mRender
        }
        if(rec.sWidth){
            c.sWidth=rec.sWidth;//宽度
        }
        c=$.extend(c,rec);
        cc.push(c);
    }
    var options=$.extend({
        iDisplayLength:25,
        bProcessing: false,
        bPaginate: true, //翻页功能
        bLengthChange: true, //改变每页显示数据数量
        bFilter: false, //过滤功能
        bSort: false, //排序功能
        bInfo: true,//页脚信息
        bAutoWidth: false,//自动宽度
        bServerSide: true, //指定从服务器端获取数据
        aoColumns:cc,
        aoColumnDefs: [{
            'targets': 0,
            'searchable':false,
            'orderable':false,
            'className': 'dt-body-center',
            'render': function (data, type, row){
                return '<input class="datatable_checkbox_select" type="checkbox" data-status="'+ row.status + '"name="id[]" value="' + row.sno + '">';
            }
        }]
    },ajaxoptions);
    return datatable.DataTable(options);
}

function dialogUpload(img,numLimit) {
    numLimit=numLimit?numLimit:1;
    var index = layer.open({
        type: 2,
        scrollbar: false,
        title: '图片上传',
        shadeClose: true,
        shade: 0.3,
        area: ['600px', '400px'],
        content: appPath+'uploadFile?img='+img+'&numLimit='+numLimit
    });
}
function previewImage(file){
    var MAXWIDTH  = 120;
    var MAXHEIGHT = 180;
    var div = document.getElementById('preview');
    var filesize=getPhotoSize(document.getElementById('previewImg'));
    if(filesize>30){
        alertError('照片最大尺寸为30KB，请重新上传');
        return;
    }

    if (file.files && file.files[0])
    {
        div.innerHTML ='<img id=imghead onclick=$("#previewImg").click()>';
        var img = document.getElementById('imghead');
        img.onload = function(){
            var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
            img.width  =  rect.width;
            img.height =  rect.height;
        }
        var reader = new FileReader();
        reader.onload = function(evt){img.src = evt.target.result;}
        reader.readAsDataURL(file.files[0]);
    }
    else //兼容IE
    {
        var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
        file.select();
        var src = document.selection.createRange().text;
        div.innerHTML = '<img id=imghead>';
        var img = document.getElementById('imghead');
        img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
        var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
        status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height);
        div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;"+sFilter+src+"\"'></div>";
    }
}
function clacImgZoomParam( maxWidth, maxHeight, width, height ){
    var param = {top:0, left:0, width:width, height:height};
    if( width>maxWidth || height>maxHeight ){
        rateWidth = width / maxWidth;
        rateHeight = height / maxHeight;

        if( rateWidth > rateHeight ){
            param.width =  maxWidth;
            param.height = Math.round(height / rateWidth);
        }else{
            param.width = Math.round(width / rateHeight);
            param.height = maxHeight;
        }
    }
    param.left = Math.round((maxWidth - param.width) / 2);
    param.top = Math.round((maxHeight - param.height) / 2);
    return param;
}
function getPhotoSize(obj){
    var photoExt=obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase();//获得文件后缀名
    if(!/^.*?\.(jpg|jpeg|png)$/.test(photoExt)){
        alertError("请上传后缀名为jpg/jpeg/png的照片!");
        return false;
    }
    var fileSize = 0;
    var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
    if (isIE && !obj.files) {
        var filePath = obj.value;
        var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
        var file = fileSystem.GetFile (filePath);
        fileSize = file.Size;
    }else {
        fileSize = obj.files[0].size;
    }
    fileSize=Math.round(fileSize/1024*100)/100; //单位为KB
    return Math.ceil(fileSize);
}






/**@2012-05-22
 * 验证输入的手机号码是否符合当前实际存在的手机号码
 * 
 */
function checkMobile(s){
	var req = new RegExp("^1[358][0-9]{9}$");
	if(!isNumber(s)){
		messageBox("请输入有效的手机号");
		return false;
	}else{
		if(s !='' && s.search(req) == -1){
			messageBox("请输入有效的手机号");
			return false;
		}else{
			return true;
		}
	}
}

function checkMobileSms(s){
	var req = new RegExp("^1[358][0-9]{9}$");
	if(!isNumber(s)){
		//messageBox("请输入有效的手机号");
		return false;
	}else{
		if(s !='' && s.search(req) == -1){
			//messageBox("请输入有效的手机号");
			return false;
		}else{
			return true;
		}
	}
}

//验证形如 带区号横杠的电话
function checkPhone(s){
	var req1 = new RegExp("^0([0-9]{2,3})\-([0-9]{7,8})$");
	var req2 = new RegExp("^0([0-9]{2,3})([0-9]{7,8})$");
	if(s !=''&& s.search(req1) == -1 && s.search(req2) == -1 ){
			return false;
	} 
	else{
		return true;
	}
}

//验证电子邮箱
function isMailBoxAddress(s){
   //对电子邮件的验证
   var myreg = /^([a-zA-Z0-9_\-]+[_|\_|\.]?)*[a-zA-Z0-9_\-]+@([a-zA-Z0-9_\-]+[_|\_|\.|\-]?)*[a-zA-Z0-9_\-]+\.[a-zA-Z]{2,3}$/;
   if(!myreg.test(s))
   {
	   return false;
   } else {
	   return true;
   }
}




 
/**
 * 是否符合Decimal类型
 * ^\d{4}\.\d{2}$
 * /^[0-9]+(\.[0-9]{0,2})?$/
 */
function isDecimal(obj) {
	if(obj != null && obj != "" && obj.length <= 13){
		if(obj.match(/^\-?[0-9]+(\.[0-9]{0,2})?$/)!=null) {
			return false;
		} else {
			return true;
		}
	}
	return true;
}

function isDecimal1(obj) {
	if(obj != null && obj != "" && obj.length <= 13){
		if(obj.match(/^\-?[0-9]+(\.[5]{0,1})?$/)!=null) {
			return false;
		} else {
			return true;
		}
	}
	return true;
}


function setCookie(name,value) {
	var days = 365;
    var exp  = new Date();
    exp.setTime(exp.getTime() + days*24*60*60*1000);
	document.cookie = name + "="+ escape(value) + ";expires=" + exp.toGMTString();;
}

function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^|)" + name + "=([^;]*)(;|$)"));
     if(arr != null) {
    	 return unescape(arr[2]); 
     }
     return null;	
}


//截取ID前缀‘page_’
function substr(str){
	var s = str.substr(5);
	return s;
}

/**
把密码强度分为四等:四种组合指 数字,小写字母,大写字母,其它字符
0. 没有输入
1. 密码长度小于或等于四位.或者密码只有一种组合
2. 密码长度大于四位, 且有两种组合.
3. 密码长度大于四位, 且有三种组合.
4. 密码长度大于四位, 且有四种组合.

*/
function evaluatePwd(word){
	var i=0;
	if(!word) {
		return i;
	}
	if(word.length <= 4){
		return 1;
	}
	if(/\d/.test(word))i++;
	if(/\W/.test(word))i++; 
	if(/[a-z]/.test(word))i++; 
	if(/[A-Z]/.test(word))i++; 
    return i;
}

function __isIE() {
	return (navigator.appVersion.indexOf("MSIE") >= 0) || (navigator.appVersion.indexOf("Trident") >= 0);
}

function __isIE6() {
	return __isIE() && !window.XMLHttpRequest;
}

function isAndroid() {
	if (/android/i.test(navigator.userAgent)){
		return true;
	}
	return false;
}

function isIos() {
	if (/ipad|iphone|mac/i.test(navigator.userAgent)){
		return true;
	}
	return false;
}
function logout() {
    createConfirm('您确定要退出系统', function () {
        window.location.href = appPath + "logout"
    })
}
function editPasswd() {
    var target = appPath+"changePwd";
    dialogBox(target, '修改密码', 600, 300);
}
$.fn.countTo = function (options) {
    options = options || {};

    return $(this).each(function () {
        // set options for current element
        var settings = $.extend({}, $.fn.countTo.defaults, {
            from:            $(this).data('from'),
            to:              $(this).data('to'),
            speed:           $(this).data('speed'),
            refreshInterval: $(this).data('refresh-interval'),
            decimals:        $(this).data('decimals')
        }, options);

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(settings.speed / settings.refreshInterval),
            increment = (settings.to - settings.from) / loops;

        // references & variables that will change with each update
        var self = this,
            $self = $(this),
            loopCount = 0,
            value = settings.from,
            data = $self.data('countTo') || {};

        $self.data('countTo', data);

        // if an existing interval can be found, clear it first
        if (data.interval) {
            clearInterval(data.interval);
        }
        data.interval = setInterval(updateTimer, settings.refreshInterval);

        // initialize the element with the starting value
        render(value);

        function updateTimer() {
            value += increment;
            loopCount++;

            render(value);

            if (typeof(settings.onUpdate) == 'function') {
                settings.onUpdate.call(self, value);
            }

            if (loopCount >= loops) {
                // remove the interval
                $self.removeData('countTo');
                clearInterval(data.interval);
                value = settings.to;

                if (typeof(settings.onComplete) == 'function') {
                    settings.onComplete.call(self, value);
                }
            }
        }

        function render(value) {
            var formattedValue = settings.formatter.call(self, value, settings);
            $self.html(formattedValue);
        }
    });
};

$.fn.countTo.defaults = {
    from: 0,               // the number the element should start at
    to: 0,                 // the number the element should end at
    speed: 1000,           // how long it should take to count between the target numbers
    refreshInterval: 100,  // how often the element should be updated
    decimals: 0,           // the number of decimal places to show
    formatter: function () {
        
    },  // handler for formatting the value before rendering
    onUpdate: null,        // callback method for every time the element is updated
    onComplete: null       // callback method for when the element finishes updating
};
function rowspan_table(table,fixmaxCol){
    var tab = document.getElementById(table);
    var  val, count, start;
    var rows=tab.tBodies[0].rows;//只处理tbody中的数据
    for(var col = fixmaxCol-1; col >= 0 ; col--){
        count = 1;
        val = "";
        for(var i=0; i<rows.length; i++){
            // if(!rows[i].cells[col]){
            //     continue
            // }
            if(val == rows[i].cells[col].innerHTML){
                count++;
            }else{
                if(count > 1){ //合并
                    start = i - count;
                    rows[start].cells[col].rowSpan = count;
                    for(var j=start+1; j<i; j++){
                        rows[j].cells[col].style.display = "none";
                    }
                    count = 1;
                }
                val = rows[i].cells[col].innerHTML;
            }
        }
        if(count > 1 ){ //合并，最后几行相同的情况下
            start = i - count;
            rows[start].cells[col].rowSpan = count;
            for(var j=start+1; j<i; j++){
                rows[j].cells[col].style.display = "none";
            }
        }
    }
};
function cons_feature(base_obj) {
    var menus=[];
    menus.push(base_obj);
    $('.navigation-accordion>li').each(function () {
        var id=$(this).find('a').attr('href');

        if(id=='#'){
            id=$(this).find('a').attr('id');
        }else{
            id=id.replace(new RegExp("/web-plat/","gm"),'')
        }
        var text=$(this).find('a').find('span').text();
        var obj={};
        obj.CODE=fixId(id.replace(new RegExp("/","gm"),'_'));
        obj.TITLE=text;
        obj.PCODE=base_obj.CODE;
        obj.CONTEXT=base_obj.CONTEXT;
        menus.push(obj);
        $(this).find('ul>li').each(function () {
            var child={};
            var cid=$(this).find('a').attr('href');
            var ctext=$(this).find('a').text();

            child.CODE=fixId(cid.substr(10,cid.length-9).replace(new RegExp("/","gm"),'_'));
            child.TITLE=ctext;
            child.PCODE=obj.CODE;
            child.CONTEXT=base_obj.CONTEXT;
            menus.push(child);
        });
    });
    // console.log(JSON.stringify(menus))
}
